import React, { useState } from "react";
import {
  StyleSheet,
  FlatList,
  Image,
  TouchableOpacity,
  View,
  TextInput,
  ScrollView,
  Dimensions,
} from "react-native";
import { useRouter } from "expo-router";
import { MaterialCommunityIcons } from "@expo/vector-icons";

import { ThemedText } from "@/components/ThemedText";
import { ThemedView } from "@/components/ThemedView";
import { Colors } from "@/constants/Colors";
import { useColorScheme } from "@/hooks/useColorScheme";

// 屏幕宽度
const { width } = Dimensions.get("window");

// 模拟社区数据
const COMMUNITY_DATA = [
  {
    id: "1",
    title: "每日健康小贴士",
    author: "健康顾问 王医生",
    content:
      "老年人应该每天保持适量运动，建议每天散步30分钟，可以有效改善心肺功能。",
    likes: 128,
    comments: 32,
    image: { uri: "https://randomuser.me/api/portraits/men/32.jpg" },
    time: "今天 08:30",
  },
  {
    id: "2",
    title: "社区太极班招募",
    author: "活动组织者 李师傅",
    content: "每周二、四、六早上7点，在中心公园举办太极班，欢迎各位老友参加！",
    likes: 89,
    comments: 45,
    image: { uri: "https://randomuser.me/api/portraits/men/45.jpg" },
    time: "昨天 14:20",
  },
  {
    id: "3",
    title: "老年人营养餐食谱分享",
    author: "营养师 张阿姨",
    content: "分享几道适合老年人的营养餐食谱，简单易做，营养均衡。",
    likes: 156,
    comments: 67,
    image: { uri: "https://randomuser.me/api/portraits/women/55.jpg" },
    time: "前天 10:15",
  },
  {
    id: "4",
    title: "棋牌室活动安排",
    author: "活动中心 赵主任",
    content: "本周末将举办象棋比赛，有兴趣的老友们请提前报名参加。",
    likes: 76,
    comments: 28,
    image: { uri: "https://randomuser.me/api/portraits/men/60.jpg" },
    time: "3天前",
  },
  {
    id: "5",
    title: "老年人智能手机使用技巧",
    author: "科技志愿者 小刘",
    content: "手把手教您使用智能手机的基本功能，让科技更好地服务于生活。",
    likes: 210,
    comments: 95,
    image: { uri: "https://randomuser.me/api/portraits/men/25.jpg" },
    time: "一周前",
  },
];

// 模拟学习课程数据
const LEARNING_DATA = [
  {
    id: "1",
    title: "太极拳入门教程",
    instructor: "李师傅",
    duration: "45分钟",
    level: "初级",
    participants: 1280,
    thumbnail: {
      uri: "https://images.unsplash.com/photo-1551854838-212c9a5eea46?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
    },
    videoUrl: "https://www.youtube.com/watch?v=hIOHGrYCEJ4",
    description:
      "适合老年人的太极拳入门课程，动作简单易学，有助于提高身体平衡性和柔韧性。",
  },
  {
    id: "2",
    title: "老年人营养健康饮食",
    instructor: "张营养师",
    duration: "30分钟",
    level: "全部",
    participants: 950,
    thumbnail: {
      uri: "https://images.unsplash.com/photo-1547592180-85f173990554?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
    },
    videoUrl: "https://www.youtube.com/watch?v=Gmh_xMMJ2Pw",
    description:
      "专为老年人设计的健康饮食指南，教您如何搭配营养均衡的膳食，保持健康活力。",
  },
  {
    id: "3",
    title: "智能手机基础操作",
    instructor: "小刘老师",
    duration: "60分钟",
    level: "初级",
    participants: 2150,
    thumbnail: {
      uri: "https://images.unsplash.com/photo-1522125670776-3c7b3e8957f1?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
    },
    videoUrl: "https://www.youtube.com/watch?v=yXWw0_UfSFg",
    description:
      "手把手教您使用智能手机的基本功能，包括拨打电话、发送短信、使用微信等常用应用。",
  },
  {
    id: "4",
    title: "老年人健康保健知识",
    instructor: "王医生",
    duration: "40分钟",
    level: "全部",
    participants: 1680,
    thumbnail: {
      uri: "https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
    },
    videoUrl: "https://www.youtube.com/watch?v=Yzm3fA2HhkQ",
    description:
      "介绍老年人常见疾病的预防保健知识，帮助您更好地管理自己的健康。",
  },
  {
    id: "5",
    title: "园艺种植基础",
    instructor: "赵园丁",
    duration: "50分钟",
    level: "初级",
    participants: 890,
    thumbnail: {
      uri: "https://images.unsplash.com/photo-1416879595882-3373a0480b5b?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
    },
    videoUrl: "https://www.youtube.com/watch?v=B0DrWAUsNSc",
    description:
      "教您在家中种植花草和蔬菜的基本技巧，享受园艺带来的乐趣和收获。",
  },
];

export default function DiscoverScreen() {
  const colorScheme = useColorScheme();
  const router = useRouter();
  const tintColor = Colors[colorScheme ?? "light"].tint;

  // 当前选中的标签
  const [activeTab, setActiveTab] = useState("community");
  // 回忆生成的输入文本
  const [memoryText, setMemoryText] = useState("");

  // 渲染社区帖子项
  const renderCommunityItem = ({ item }) => (
    <TouchableOpacity
      style={styles.communityItem}
      onPress={() => {
        // 导航到社区帖子详情页面
        router.push(`/community/${item.id}`);
      }}
    >
      <View style={styles.postHeader}>
        <View style={styles.authorContainer}>
          <Image source={item.image} style={styles.authorAvatar} />
          <View>
            <ThemedText style={styles.postTitle}>{item.title}</ThemedText>
            <ThemedText style={styles.authorText}>{item.author}</ThemedText>
          </View>
        </View>
        <ThemedText style={styles.timeText}>{item.time}</ThemedText>
      </View>

      <ThemedText
        style={styles.contentText}
        numberOfLines={3}
        ellipsizeMode='tail'
      >
        {item.content}
      </ThemedText>

      <View style={styles.postFooter}>
        <View style={styles.actionButton}>
          <MaterialCommunityIcons name='heart-outline' size={24} color='#888' />
          <ThemedText style={styles.actionText}>{item.likes}</ThemedText>
        </View>
        <View style={styles.actionButton}>
          <MaterialCommunityIcons
            name='comment-outline'
            size={24}
            color='#888'
          />
          <ThemedText style={styles.actionText}>{item.comments}</ThemedText>
        </View>
        <View style={styles.actionButton}>
          <MaterialCommunityIcons name='share-outline' size={24} color='#888' />
          <ThemedText style={styles.actionText}>分享</ThemedText>
        </View>
      </View>
    </TouchableOpacity>
  );

  // 渲染学习课程项
  const renderLearningItem = ({ item }) => (
    <TouchableOpacity
      style={styles.courseItem}
      onPress={() => {
        // 打开视频链接
        router.push(item.videoUrl);
      }}
    >
      <Image source={item.thumbnail} style={styles.courseThumbnail} />
      <View style={styles.courseInfo}>
        <ThemedText style={styles.courseTitle}>{item.title}</ThemedText>
        <View style={styles.courseDetails}>
          <View style={styles.courseDetail}>
            <MaterialCommunityIcons name='account' size={16} color='#0a7ea4' />
            <ThemedText style={styles.courseDetailText}>
              {item.instructor}
            </ThemedText>
          </View>
          <View style={styles.courseDetail}>
            <MaterialCommunityIcons
              name='clock-outline'
              size={16}
              color='#0a7ea4'
            />
            <ThemedText style={styles.courseDetailText}>
              {item.duration}
            </ThemedText>
          </View>
          <View style={styles.courseDetail}>
            <MaterialCommunityIcons name='signal' size={16} color='#0a7ea4' />
            <ThemedText style={styles.courseDetailText}>
              {item.level}
            </ThemedText>
          </View>
        </View>
        <ThemedText
          style={styles.courseDescription}
          numberOfLines={2}
          ellipsizeMode='tail'
        >
          {item.description}
        </ThemedText>
        <View style={styles.courseFooter}>
          <View style={styles.participantsContainer}>
            <MaterialCommunityIcons
              name='account-group'
              size={16}
              color='#0a7ea4'
            />
            <ThemedText style={styles.participantsText}>
              {item.participants}人学习
            </ThemedText>
          </View>
          <View style={styles.playButton}>
            <ThemedText style={styles.playButtonText}>开始学习</ThemedText>
            <MaterialCommunityIcons name='play-circle' size={18} color='#fff' />
          </View>
        </View>
      </View>
    </TouchableOpacity>
  );

  // 渲染回忆生成界面
  const renderMemoryTab = () => (
    <ScrollView style={styles.memoryContainer}>
      <View style={styles.memoryHeader}>
        <ThemedText style={styles.memoryTitle}>回忆生成</ThemedText>
        <ThemedText style={styles.memorySubtitle}>
          通过描述或上传图片，AI将帮您重现珍贵回忆
        </ThemedText>
      </View>

      <View style={styles.memoryInputContainer}>
        <TextInput
          style={styles.memoryTextInput}
          placeholder='描述您想要重现的回忆场景，例如：我20岁时在北京天安门前的合影...'
          placeholderTextColor='#999'
          multiline
          numberOfLines={4}
          value={memoryText}
          onChangeText={setMemoryText}
        />
      </View>

      <View style={styles.uploadSection}>
        <TouchableOpacity style={styles.uploadButton}>
          <MaterialCommunityIcons name='image-plus' size={28} color='#fff' />
          <ThemedText style={styles.uploadButtonText}>上传照片</ThemedText>
        </TouchableOpacity>
        <ThemedText style={styles.uploadHint}>
          上传老照片可以帮助AI更准确地还原场景
        </ThemedText>
      </View>

      <TouchableOpacity
        style={[
          styles.generateButton,
          !memoryText && styles.generateButtonDisabled,
        ]}
        disabled={!memoryText}
      >
        <MaterialCommunityIcons name='refresh' size={24} color='#fff' />
        <ThemedText style={styles.generateButtonText}>生成回忆</ThemedText>
      </TouchableOpacity>

      <View style={styles.examplesSection}>
        <ThemedText style={styles.examplesTitle}>回忆示例</ThemedText>
        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          style={styles.examplesScrollView}
        >
          <TouchableOpacity style={styles.exampleItem}>
            <Image
              source={{
                uri: "https://images.unsplash.com/photo-1533294455009-a77b7557d2d1?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
              }}
              style={styles.exampleImage}
            />
            <ThemedText style={styles.exampleText}>童年的老家院子</ThemedText>
          </TouchableOpacity>
          <TouchableOpacity style={styles.exampleItem}>
            <Image
              source={{
                uri: "https://images.unsplash.com/photo-1575517111839-3a3843ee7f5d?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
              }}
              style={styles.exampleImage}
            />
            <ThemedText style={styles.exampleText}>大学同学聚会</ThemedText>
          </TouchableOpacity>
          <TouchableOpacity style={styles.exampleItem}>
            <Image
              source={{
                uri: "https://images.unsplash.com/photo-1551696785-927d4ac2d35b?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
              }}
              style={styles.exampleImage}
            />
            <ThemedText style={styles.exampleText}>80年代的北京街头</ThemedText>
          </TouchableOpacity>
          <TouchableOpacity style={styles.exampleItem}>
            <Image
              source={{
                uri: "https://images.unsplash.com/photo-1517457373958-b7bdd4587205?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
              }}
              style={styles.exampleImage}
            />
            <ThemedText style={styles.exampleText}>年轻时的婚礼</ThemedText>
          </TouchableOpacity>
        </ScrollView>
      </View>
    </ScrollView>
  );

  // 渲染顶部标签栏
  const renderTabBar = () => (
    <View style={styles.tabBar}>
      <TouchableOpacity
        style={[
          styles.tabItem,
          activeTab === "community" && styles.activeTabItem,
        ]}
        onPress={() => setActiveTab("community")}
      >
        <ThemedText
          style={[
            styles.tabText,
            activeTab === "community" && styles.activeTabText,
          ]}
        >
          社区
        </ThemedText>
      </TouchableOpacity>
      <TouchableOpacity
        style={[styles.tabItem, activeTab === "memory" && styles.activeTabItem]}
        onPress={() => setActiveTab("memory")}
      >
        <ThemedText
          style={[
            styles.tabText,
            activeTab === "memory" && styles.activeTabText,
          ]}
        >
          回忆
        </ThemedText>
      </TouchableOpacity>
      <TouchableOpacity
        style={[
          styles.tabItem,
          activeTab === "learning" && styles.activeTabItem,
        ]}
        onPress={() => setActiveTab("learning")}
      >
        <ThemedText
          style={[
            styles.tabText,
            activeTab === "learning" && styles.activeTabText,
          ]}
        >
          学习
        </ThemedText>
      </TouchableOpacity>
    </View>
  );

  // 根据当前选中的标签渲染对应的内容
  const renderContent = () => {
    switch (activeTab) {
      case "community":
        return (
          <FlatList
            data={COMMUNITY_DATA}
            renderItem={renderCommunityItem}
            keyExtractor={(item) => item.id}
            contentContainerStyle={styles.listContent}
          />
        );
      case "memory":
        return renderMemoryTab();
      case "learning":
        return (
          <FlatList
            data={LEARNING_DATA}
            renderItem={renderLearningItem}
            keyExtractor={(item) => item.id}
            contentContainerStyle={[
              styles.listContent,
              styles.learningListContent,
            ]}
            showsVerticalScrollIndicator={false}
          />
        );
      default:
        return null;
    }
  };

  return (
    <ThemedView style={styles.container}>
      <View style={styles.header}>
        <ThemedText style={styles.headerTitle}>发现</ThemedText>
      </View>
      {renderTabBar()}
      {renderContent()}
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    paddingTop: 60,
    paddingBottom: 15,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: "#E1E1E1",
    backgroundColor: "#FFFFFF",
  },
  headerTitle: {
    fontSize: 28,
    fontWeight: "bold",
    color: "#333",
  },
  tabBar: {
    flexDirection: "row",
    borderBottomWidth: 1,
    borderBottomColor: "#E1E1E1",
    backgroundColor: "#FFFFFF",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.05,
    shadowRadius: 3,
    elevation: 3,
    zIndex: 10,
  },
  tabItem: {
    flex: 1,
    alignItems: "center",
    paddingVertical: 15,
  },
  activeTabItem: {
    borderBottomWidth: 3,
    borderBottomColor: "#0a7ea4",
  },
  tabText: {
    fontSize: 16,
    fontWeight: "500",
    color: "#666",
  },
  activeTabText: {
    color: "#0a7ea4",
    fontWeight: "bold",
  },
  listContent: {
    paddingVertical: 10,
  },
  learningListContent: {
    paddingHorizontal: 12,
    paddingBottom: 20,
    backgroundColor: "#f8f9fa",
  },
  // 社区样式
  communityItem: {
    padding: 15,
    borderBottomWidth: 1,
    borderBottomColor: "#E1E1E1",
    backgroundColor: "#FFFFFF",
  },
  postHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-start",
    marginBottom: 10,
  },
  authorContainer: {
    flexDirection: "row",
    alignItems: "center",
  },
  authorAvatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    marginRight: 10,
  },
  postTitle: {
    fontSize: 18,
    fontWeight: "bold",
    marginBottom: 4,
  },
  authorText: {
    fontSize: 14,
    color: "#666",
  },
  timeText: {
    fontSize: 14,
    color: "#888",
  },
  contentText: {
    fontSize: 16,
    lineHeight: 22,
    marginBottom: 15,
  },
  postFooter: {
    flexDirection: "row",
    justifyContent: "space-between",
    paddingTop: 10,
  },
  actionButton: {
    flexDirection: "row",
    alignItems: "center",
  },
  actionText: {
    marginLeft: 5,
    fontSize: 14,
    color: "#888",
  },
  // 学习样式
  courseItem: {
    margin: 10,
    marginBottom: 20,
    borderRadius: 16,
    backgroundColor: "#FFFFFF",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 3 },
    shadowOpacity: 0.1,
    shadowRadius: 6,
    elevation: 5,
    overflow: "hidden",
  },
  courseThumbnail: {
    width: "100%",
    height: 180,
    borderTopLeftRadius: 16,
    borderTopRightRadius: 16,
  },
  courseInfo: {
    padding: 16,
  },
  courseTitle: {
    fontSize: 20,
    fontWeight: "bold",
    marginBottom: 12,
    color: "#333",
  },
  courseDetails: {
    flexDirection: "row",
    flexWrap: "wrap",
    marginBottom: 12,
    backgroundColor: "#f8f9fa",
    borderRadius: 8,
    padding: 10,
  },
  courseDetail: {
    flexDirection: "row",
    alignItems: "center",
    marginRight: 16,
    marginBottom: 6,
    backgroundColor: "rgba(10, 126, 164, 0.08)",
    paddingVertical: 6,
    paddingHorizontal: 10,
    borderRadius: 20,
  },
  courseDetailText: {
    fontSize: 14,
    color: "#444",
    marginLeft: 6,
    fontWeight: "500",
  },
  courseDescription: {
    fontSize: 16,
    color: "#555",
    marginBottom: 16,
    lineHeight: 22,
  },
  courseFooter: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    borderTopWidth: 1,
    borderTopColor: "#eee",
    paddingTop: 12,
    marginTop: 4,
  },
  participantsContainer: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#f0f0f0",
    paddingVertical: 6,
    paddingHorizontal: 12,
    borderRadius: 20,
  },
  participantsText: {
    fontSize: 14,
    color: "#555",
    marginLeft: 6,
    fontWeight: "500",
  },
  playButton: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#0a7ea4",
    paddingVertical: 8,
    paddingHorizontal: 16,
    borderRadius: 20,
  },
  playButtonText: {
    fontSize: 15,
    color: "#fff",
    marginRight: 6,
    fontWeight: "600",
  },
  // 回忆样式
  memoryContainer: {
    flex: 1,
    padding: 15,
    backgroundColor: "#f8f9fa",
  },
  memoryHeader: {
    marginBottom: 25,
    backgroundColor: "rgba(10, 126, 164, 0.05)",
    padding: 15,
    borderRadius: 12,
    borderLeftWidth: 4,
    borderLeftColor: "#0a7ea4",
  },
  memoryTitle: {
    fontSize: 26,
    fontWeight: "bold",
    color: "#0a7ea4",
    marginBottom: 8,
  },
  memorySubtitle: {
    fontSize: 16,
    color: "#666",
    lineHeight: 22,
  },
  memoryInputContainer: {
    backgroundColor: "#fff",
    borderRadius: 12,
    padding: 15,
    marginBottom: 20,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  memoryTextInput: {
    height: 120,
    textAlignVertical: "top",
    fontSize: 16,
    padding: 12,
    borderWidth: 1,
    borderColor: "#E1E1E1",
    borderRadius: 8,
    backgroundColor: "#fafafa",
  },
  uploadSection: {
    alignItems: "center",
    marginBottom: 25,
  },
  uploadButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#0a7ea4",
    paddingVertical: 12,
    paddingHorizontal: 20,
    borderRadius: 25,
    marginBottom: 10,
    width: "80%",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 3,
    elevation: 4,
  },
  uploadButtonText: {
    color: "#fff",
    fontSize: 16,
    fontWeight: "600",
    marginLeft: 8,
  },
  uploadHint: {
    fontSize: 14,
    color: "#888",
    textAlign: "center",
  },
  generateButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#4CAF50",
    paddingVertical: 15,
    borderRadius: 30,
    marginBottom: 30,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 3 },
    shadowOpacity: 0.2,
    shadowRadius: 4,
    elevation: 5,
  },
  generateButtonDisabled: {
    backgroundColor: "#A5D6A7",
    shadowOpacity: 0.1,
    elevation: 2,
  },
  generateButtonText: {
    color: "#fff",
    fontSize: 18,
    fontWeight: "bold",
    marginLeft: 10,
  },
  examplesSection: {
    marginBottom: 20,
  },
  examplesTitle: {
    fontSize: 20,
    fontWeight: "600",
    marginBottom: 15,
    color: "#333",
  },
  examplesScrollView: {
    marginBottom: 10,
  },
  exampleItem: {
    marginRight: 15,
    width: width * 0.6,
    borderRadius: 12,
    overflow: "hidden",
    backgroundColor: "#fff",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  exampleImage: {
    width: "100%",
    height: 150,
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
  },
  exampleText: {
    padding: 12,
    fontSize: 16,
    fontWeight: "500",
    textAlign: "center",
  },
});
